<template>
  <div class="anime-card" :class="{ 'featured': isFeatured, 'rank-1': rank === 1, 'rank-2': rank === 2, 'rank-3': rank === 3 }" @click="showAnimeDetail">
    <!-- 排名标识已移除，改为在父组件中显示 -->
    
    <!-- 动漫封面 -->
    <div class="anime-image-container">
      <CustomImage 
        :src="anime.coverImageUrl" 
        :alt="anime.title" 
        customClass="anime-image"
        @error="onImageError"
      />
    </div>
    
    <!-- 动漫信息 -->
      <div class="anime-info">
        <h3 class="anime-title">{{ anime.title }}</h3>
        
        <!-- 动漫类型 -->
        <div v-if="anime.type" class="anime-type">{{ anime.type }}</div>
        
        <!-- 动漫简介 -->
        <p v-if="anime.description" class="anime-description">{{ anime.description }}</p>
        
        <div class="anime-meta">
          <div class="rating">
            <span class="rating-icon">★</span>
            <span class="rating-value">{{ anime.rating || '暂无评分' }}</span>
          </div>
          
          <div v-if="showVotes" class="votes">
            <span class="votes-icon">👍</span>
            <span class="votes-value">{{ anime.votes || 0 }}票</span>
          </div>
          
          <div v-if="showFavoritesCount" class="favorites">
            <span class="favorites-icon">☆</span>
            <span class="favorites-value">{{ anime.favorites || 0 }}收藏</span>
          </div>
        </div>
      
      <!-- 投票和收藏按钮组 -->
      <div class="action-buttons">
        <div class="buttons-container">
          <!-- 投票按钮 - 使用全局VoteButton组件 -->
          <VoteButton 
            v-if="showVoteButton" 
            :anime-id="anime.id"
            @vote="onVote($event)"
          />
          
          <!-- 收藏按钮 -->
          <button 
            v-if="showFavoriteButton"
            class="favorite-button"
            :class="{ 'favorited': isFavorited }"
            :disabled="isFavoriting"
            @click.stop="handleFavorite"
          >
            <span class="favorite-icon">☆</span>
            <span v-if="isFavoriting">收藏中...</span>
            <span v-else-if="isFavorited">已收藏</span>
            <span v-else>收藏</span>
          </button>
        </div>
      </div>
      
      <!-- 提名按钮（仅在提名页面显示） -->
      <button 
        v-if="showNominateButton" 
        class="nominate-button"
        :disabled="isNominating"
        @click.stop="handleNominate"
      >
        <span v-if="isNominating">提名中...</span>
        <span v-else>提名</span>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { Anime } from '../types/anime.ts'
import toastService from '../services/toastService'
import { GLOBAL_CONFIG } from '../config'
import { checkFavorite } from '../services/favoriteService'
import { isAuthenticated } from '../services/userService'
import CustomImage from './common/CustomImage.vue'
import VoteButton from './common/VoteButton.vue'

// 定义组件的属性
const props = withDefaults(defineProps<{
  anime: Anime
  rank?: number
  showRank?: boolean
  showVoteButton?: boolean
  showNominateButton?: boolean
  showFavoriteButton?: boolean
  showVotes?: boolean
  showFavoritesCount?: boolean
  isFeatured?: boolean
}>(), {
  rank: 0,
  showFavoriteButton: true,
  showVotes: true,
  showFavoritesCount: true,
  showRank: true,
  showVoteButton: true,
  showNominateButton: false,
  isFeatured: false
})

// 定义组件的事件
const emit = defineEmits<{
  vote: [animeId: number]
  nominate: [anime: Anime]
  favorite: [eventData: number | { animeId: number, isFavorited: boolean }]
  click: [anime: Anime]
  'show-detail': [anime: Anime]
}>()

// 组件内部状态
const isNominating = ref(false)
const isFavorited = ref(false)
const isFavoriting = ref(false)

// 移除了处理图片URL的计算属性，因为CustomImage组件会自动处理

// 组件挂载时检查收藏状态和重置投票状态
onMounted(async () => {
  await checkFavoriteStatus()
})

// 检查用户是否已收藏
const checkFavoriteStatus = async () => {
  // 优先使用anime对象中的isFavorite属性（从父组件传递）
  if (props.anime.isFavorite !== undefined) {
    isFavorited.value = props.anime.isFavorite
    return
  }
  
  // 如果用户已登录，调用API检查收藏状态
  if (isAuthenticated()) {
    try {
      const animeId = typeof props.anime.id === 'string' ? parseInt(props.anime.id) : props.anime.id
      const isFavorite = await checkFavorite(animeId)
      isFavorited.value = isFavorite
      return
    } catch (error) {
      console.error('检查收藏状态失败:', error)
      // API调用失败时，回退到localStorage
    }
  }
  
  // 回退到从localStorage获取
  const favorites = localStorage.getItem('favorites')
  if (favorites) {
    try {
      const favoriteIds = JSON.parse(favorites) as Array<string | number>
      isFavorited.value = favoriteIds.includes(props.anime.id.toString()) || favoriteIds.includes(props.anime.id)
    } catch (error) {
      console.error('解析收藏列表失败:', error)
    }
  }
}

// 处理投票事件
const onVote = (animeId: number) => {
  // 直接触发投票事件给父组件，由父组件统一处理API调用
  emit('vote', animeId)
}
  
  // 移除未使用的导入

// 处理收藏
const handleFavorite = async () => {
  if (isFavoriting.value) return
  
  // 检查用户是否已登录
  const user = localStorage.getItem('user')
  if (!user) {
    // 显示登录提示
    if ((window as any).showLoginModal) {
      (window as any).showLoginModal('请先登录后再收藏！')
    } else {
      toastService.info('请先登录后再收藏！')
    }
    return
  }
  
  // 开始收藏过程
  isFavoriting.value = true
  
  try {
    // 保存操作前的收藏状态
    const wasFavorited = isFavorited.value
    
    // 更新组件自身UI状态为加载中
    isFavoriting.value = true
    
    // 只触发收藏事件，API调用和数据处理由父组件负责
    // 这样可以避免子组件和父组件重复调用API
    emit('favorite', {
      animeId: props.anime.id,
      isFavorited: wasFavorited
    })
    
    // 直接乐观更新UI状态（父组件会负责实际的API调用和数据更新）
    isFavorited.value = !wasFavorited
    
  } catch (error) {
    console.error('收藏操作失败:', error)
    // 错误时回滚状态
    isFavorited.value = !isFavorited.value
    // 错误信息已通过axios拦截器或服务层显示，此处不显示额外信息
  } finally {
    isFavoriting.value = false
  }
}

// 处理提名
const handleNominate = async () => {
  if (isNominating.value) return
  
  // 检查用户是否已登录
  const user = localStorage.getItem('user')
  if (!user) {
    // 显示登录提示
    if ((window as any).showLoginModal) {
      (window as any).showLoginModal()
    } else {
      toastService.info('请先登录后再提名！')
    }
    return
  }
  
  // 模拟提名过程
  isNominating.value = true
  
  try {
    // 模拟API调用延迟
    // await new Promise(resolve => setTimeout(resolve, 500))
    
    // 触发提名事件，传递完整的anime对象
    emit('nominate', props.anime)
    
    // alert(`已提名《${props.anime.title}》！`)
    
  } catch (error) {
    console.error('提名失败:', error)
    // alert('提名失败，请稍后再试！')
  } finally {
    isNominating.value = false
  }
}

// 显示动漫详情
const showAnimeDetail = () => {
  emit('click', props.anime)
}

// 处理图片加载失败，设置默认图片
const onImageError = (event?: Event) => {
  if (event) {
    const target = event.target as HTMLImageElement
    target.src = GLOBAL_CONFIG.DEFAULT_IMAGE_PATH
  }
}

// 为了方便父组件通过ref重置状态，暴露空方法保持兼容性
defineExpose({
  resetVotingStatus: () => {}
})

// 组件挂载时检查收藏状态
checkFavoriteStatus()
</script>
<style>
/* 动漫卡片基础样式 - 苹果风格 */
.anime-card {
  background-color: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: row;
  cursor: pointer;
}

/* 前三名卡片渐变背景 */
.anime-card.rank-1 {
  background: linear-gradient(135deg, #FFD700 0%, #FFFFFF 100%);
}

.anime-card.rank-2 {
  background: linear-gradient(135deg, #C0C0C0 0%, #FFFFFF 100%);
}

.anime-card.rank-3 {
  background: linear-gradient(135deg, #CD7F32 0%, #FFFFFF 100%);
  opacity: 0.95;
}

.anime-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

/* 特色卡片样式 */
.anime-card.featured {
  flex-direction: row;
  height: 240px;
}

/* 排名标识 */
.rank-badge {
  position: absolute;
  top: 12px;
  left: 12px;
  background-color: #FF69B4;
  color: white;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 0.875rem;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.3);
}

/* 排名样式 */
.rank-badge-1 {
  background-color: #FFD700; /* 金色 */
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.5);
  font-size: 1rem;
}

.rank-badge-2 {
  background-color: #C0C0C0; /* 银色 */
  box-shadow: 0 2px 8px rgba(192, 192, 192, 0.5);
}

.rank-badge-3 {
  background-color: #CD7F32; /* 铜色 */
  box-shadow: 0 2px 8px rgba(205, 127, 50, 0.4);
  opacity: 0.85;
}

/* 动漫封面容器 */
.anime-image-container {
  width: 100%;
  aspect-ratio: 2/3;
  overflow: hidden;
  position: relative;
}

.anime-card.featured .anime-image-container {
  width: 35%;
  aspect-ratio: 3/4;
}

/* 前三名图片位置优化 */
.anime-card.rank-1 .anime-image-container,
.anime-card.rank-2 .anime-image-container,
.anime-card.rank-3 .anime-image-container {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.anime-card.rank-1 .anime-image,
.anime-card.rank-2 .anime-image,
.anime-card.rank-3 .anime-image {
  object-position: center;
  min-height: 180px;
}

/* 动漫封面图片 */
.anime-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
  min-height: 160px;
}

/* 统一动漫主图大小 */
.anime-image-container {
  width: 120px;
  height: 160px;
  overflow: hidden;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.anime-card.featured .anime-image-container {
  width: 35%;
  height: 200px;
}

/* 排行榜前三名图片大小依次递减 */
.anime-card.rank-1 .anime-image-container {
  width: 200px;
  height: 240px;
}

.anime-card.rank-2 .anime-image-container {
  width: 180px;
  height: 220px;
}

.anime-card.rank-3 .anime-image-container {
  width: 160px;
  height: 200px;
}

.anime-card:hover .anime-image {
  transform: scale(1.05);
}

/* 特色卡片图片 */
.anime-card.featured .anime-image {
  height: 100%;
}

/* 加载失败的图片样式 */
.anime-image[src*="placeholder"] {
  background-color: #F2F2F7;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8E8E93;
  font-size: 0.875rem;
  text-align: center;
  padding: 16px;
}

/* 动漫信息区域 */
.anime-info {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.anime-card.featured .anime-info {
  padding: 20px;
}

/* 动漫标题 */
.anime-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1C1C1E;
  margin-bottom: 12px;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.anime-card.featured .anime-title {
  font-size: 1.25rem;
  -webkit-line-clamp: 3;
}

/* 动漫元数据 */
.anime-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  flex-wrap: wrap;
  flex: 1;
}

.anime-card.featured .anime-meta {
  margin-bottom: auto;
}

/* 评分样式 */
.rating {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
  color: #FFD700;
}

.rating-icon {
  font-size: 1.125rem;
}

/* 投票数样式 */
.votes {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
  color: #6C6C70;
}

.votes-icon {
  font-size: 1.125rem;
}

/* 操作按钮组 */
.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: auto;
  width: 100%;
}

/* 按钮容器 */
.buttons-container {
  display: flex;
  gap: 8px;
}

/* 投票按钮 */
.vote-button {
  flex: 1;
  background-color: #FF69B4;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 8px;
  font-weight: 500;
  font-size: 0.875rem;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  white-space: nowrap;
}

.vote-button:hover:not(:disabled) {
  background-color: #FF1493;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.25);
}

.vote-button.voted {
  background-color: #34C759;
}

.vote-button.voted:hover:not(:disabled) {
  background-color: #30B053;
  box-shadow: 0 2px 8px rgba(52, 199, 89, 0.25);
}

/* 收藏数样式 */
.favorites {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
  color: #FF69B4;
}

.favorites-icon {
  font-size: 1.125rem;
}

/* 收藏按钮 */
.favorite-button {
  flex: 1;
  background-color: #FF69B4;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 8px;
  font-weight: 500;
  font-size: 0.875rem;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  white-space: nowrap;
}

.favorite-button:hover:not(:disabled) {
  background-color: #FF1493;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.25);
}

.favorite-button:hover:not(:disabled) {
  background-color: #FFE6F2;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.25);
}

.favorite-button.favorited {
  background-color: #FF69B4;
  color: white;
}

.favorite-button.favorited:hover:not(:disabled) {
  background-color: #FF1493;
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.25);
}

/* 提名按钮 */
.nominate-button {
  width: 100%;
  background-color: #FF9500;
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 12px;
  font-weight: 500;
  transition: all 0.2s ease;
  margin-top: auto;
}

.nominate-button:hover:not(:disabled) {
  background-color: #FF8C00;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(255, 149, 0, 0.25);
}

/* 动漫类型 */
.anime-type {
  font-size: 0.75rem;
  font-weight: 500;
  margin-bottom: 8px;
  display: inline-block;
}

/* 动画描述 */
.anime-description {
  color: #6C6C70;
  font-size: 0.875rem;
  line-height: 1.5;
  /* margin-bottom: 16px; */
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.anime-card.featured .anime-description {
  -webkit-line-clamp: 4;
}

/* 动漫详情 */
.anime-details {
  margin-top: 12px;
  font-size: 0.875rem;
  color: #6C6C70;
}

.anime-detail-item {
  margin-bottom: 4px;
}

.anime-detail-label {
  font-weight: 500;
}

.anime-detail-value {
  color: #1C1C1E;
  margin-left: 4px;
}

/* 骨架屏样式 */
.skeleton {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  border-radius: 8px;
}

@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  /* 特色卡片响应式 */
  .anime-card.featured {
    height: auto;
    flex-direction: column;
  }
  
  .anime-card.featured .anime-image-container {
    width: 100%;
    height: 220px;
  }
  
  .anime-card.featured .anime-info {
    padding: 16px;
  }
  
  /* 前三名卡片响应式 */
  .anime-card.rank-1 {
    background: linear-gradient(135deg, #FFD700 0%, #FFFFFF 100%);
  }
  
  .anime-card.rank-2 {
    background: linear-gradient(135deg, #C0C0C0 0%, #FFFFFF 100%);
  }
  
  .anime-card.rank-3 {
    background: linear-gradient(135deg, #CD7F32 0%, #FFFFFF 100%);
  }
}

@media (max-width: 480px) {
  .anime-card {
    border-radius: 12px;
    flex-direction: column;
  }
  
  .anime-info {
    padding: 12px;
  }
  
  .anime-title {
    font-size: 1rem;
  }
  
  .anime-meta {
    gap: 12px;
    margin-bottom: 12px;
  }
  
  .anime-image-container {
    width: 100%;
    height: 200px;
  }
  
  .anime-image {
    min-height: 200px;
  }
  
  /* 前三名卡片响应式 - 小屏幕 */
  .anime-card.rank-1 {
    background: linear-gradient(135deg, #FFD700 0%, #FFFFFF 100%);
  }
  
  .anime-card.rank-2 {
    background: linear-gradient(135deg, #C0C0C0 0%, #FFFFFF 100%);
  }
  
  .anime-card.rank-3 {
    background: linear-gradient(135deg, #CD7F32 0%, #FFFFFF 100%);
  }
  
  /* 排名徽章响应式 */
  .rank-badge {
    top: 8px;
    left: 8px;
    width: 24px;
    height: 24px;
    font-size: 0.75rem;
  }
  
  /* 简介文本响应式 */
  .anime-description {
    font-size: 0.8125rem;
    margin-bottom: 12px;
  }
}

/* 高对比度模式支持 */
@media (prefers-contrast: high) {
  .anime-card {
    background-color: #ffffff;
    border: 2px solid #000000;
  }
  
  .rank-badge {
    border: 2px solid #000000;
  }
}

/* 减少动画偏好支持 */
@media (prefers-reduced-motion: reduce) {
  .anime-card:hover {
    transform: none;
  }
  
  .anime-card:hover .anime-image {
    transform: none;
  }
  
  .vote-button:hover:not(:disabled),
  .favorite-button:hover:not(:disabled),
  .nominate-button:hover:not(:disabled) {
    transform: none;
  }
}
</style>